<template>
  <div class="intelligence-graph-page">
    <div class="graph-content">
      <!-- 左侧筛选面板 -->
      <div class="filter-panel">
        <div class="filter-section">
          <h3>筛选条件</h3>

          <!-- 部门 -->
          <div class="filter-item">
            <label>部门:</label>
            <el-select
              v-model="filters.department"
              @change="handleFilterChange"
              clearable
              placeholder="全部部门"
            >
              <el-option
                v-for="dept in filterOptions.departments"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
              />
            </el-select>
          </div>

          <!-- 风险等级 -->
          <div class="filter-item">
            <label>风险等级:</label>
            <el-checkbox-group
              v-model="filters.riskLevels"
              @change="handleFilterChange"
            >
              <el-checkbox
                v-for="level in filterOptions.riskLevels"
                :key="level.value"
                :label="level.value"
              >
                <span :style="{ color: level.color }">{{ level.label }}</span>
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <!-- 资产类型 -->
          <!-- <div class="filter-item">
            <label>资产类型:</label>
            <el-checkbox-group
              v-model="filters.assetTypes"
              @change="handleFilterChange"
            >
              <el-checkbox
                v-for="type in filterOptions.assetTypes"
                :key="type.value"
                :label="type.value"
              >
                {{ type.label }} ({{ type.count }})
              </el-checkbox>
            </el-checkbox-group>
          </div> -->

          <!-- 漏洞严重程度 -->
          <div class="filter-item">
            <label>漏洞严重程度:</label>
            <el-checkbox-group
              v-model="filters.severity"
              @change="handleFilterChange"
            >
              <el-checkbox
                v-for="level in filterOptions.severityLevels"
                :key="level.value"
                :label="level.value"
              >
                <span :style="{ color: level.color }">{{ level.label }}</span>
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <!-- 数据量限制 -->
          <div class="filter-item">
            <label>数据量限制:</label>
            <el-select
              v-model="filters.limit"
              @change="handleFilterChange"
              clearable
            >
              <el-option
                v-for="opt in filterOptions.limitOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </div>

          <div class="filter-actions">
            <el-button @click="resetFilters">重置</el-button>
            <el-button type="primary" @click="applyFilters">应用筛选</el-button>
          </div>
        </div>

        <!-- 节点统计 -->
        <div class="statistics-section">
          <h3>节点统计</h3>
          <div class="statistics-list">
            <div class="statistics-item">
              总资产: {{ statistics.totalAssets }}个
            </div>
            <div class="statistics-item">
              总漏洞: {{ statistics.totalVulnerabilities }}个
            </div>
            <div class="statistics-item">
              平均漏洞数:
              {{ (statistics.avgVulnerabilitiesPerAsset || 0).toFixed(2) }}
            </div>
            <div class="statistics-item">
              部门数: {{ statistics.departmentCount }}个
            </div>
          </div>

          <div class="statistics-subsection">
            <h4>风险分布</h4>
            <div class="statistics-list">
              <div class="statistics-item">
                <span class="risk-badge high"></span>
                <span>高风险</span>
                {{ statistics.riskDistribution.high }}个
              </div>
              <div class="statistics-item">
                <span class="risk-badge medium"></span>
                <span>中风险</span>
                {{ statistics.riskDistribution.medium }}个
              </div>
              <div class="statistics-item">
                <span class="risk-badge low"></span>
                <span>低风险</span>
                {{ statistics.riskDistribution.low }}个
              </div>
              <div class="statistics-item">
                <span class="risk-badge safe"></span>
                <span>安全</span>
                {{ statistics.riskDistribution.safe }}个
              </div>
            </div>
          </div>

          <div class="statistics-subsection">
            <h4>严重程度分布</h4>
            <div class="statistics-list">
              <div class="statistics-item">
                <span class="severity-badge critical"></span>
                <span>严重</span>
                {{ statistics.severityDistribution.critical }}个
              </div>
              <div class="statistics-item">
                <span class="severity-badge high"></span>
                <span>高危</span>
                {{ statistics.severityDistribution.high }}个
              </div>
              <div class="statistics-item">
                <span class="severity-badge medium"></span>
                <span>中危</span>
                {{ statistics.severityDistribution.medium }}个
              </div>
              <div class="statistics-item">
                <span class="severity-badge low"></span>
                <span>低危</span>
                {{ statistics.severityDistribution.low }}个
              </div>
            </div>
          </div>

          <div
            v-if="statistics.topDepartments.length > 0"
            class="statistics-subsection"
          >
            <h4>部门排行</h4>
            <div class="statistics-list">
              <div
                v-for="(dept, index) in statistics.topDepartments.slice(0, 5)"
                :key="index"
                class="statistics-item"
              >
                {{ dept.department }}: {{ dept.asset_count }}个资产,
                {{ dept.vulnerability_count }}个漏洞
              </div>
            </div>
          </div>
        </div>

        <!-- 图例 -->
        <div class="legend-section">
          <h3>图例</h3>
          <div class="statistics-list">
            <div class="statistics-item">
              <span class="legend-icon department"></span>
              <span>部门</span>
            </div>
            <div class="statistics-item">
              <span class="legend-icon asset"></span>
              <span>资产</span>
            </div>
            <div class="statistics-item">
              <span class="legend-icon vulnerability"></span>
              <span>漏洞</span>
            </div>
            <div class="statistics-item">
              <span class="legend-icon alert"></span>
              <span>告警</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间图谱区域 -->
      <div class="graph-area">
        <div class="graph-toolbar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索节点..."
            @keyup.enter="searchNodes"
            class="search-input"
          >
            <template #append>
              <el-button @click="searchNodes"> 搜索 </el-button>
            </template>
          </el-input>

          <div class="graph-actions">
            <!-- <el-select
              v-model="currentLayout"
              @change="changeLayout"
              style="width: 120px; margin-right: 10px"
            >
              <el-option label="环形布局" value="circular" />
              <el-option label="力导向" value="force" />
            </el-select> -->

            <el-button @click="refreshGraph"> 刷新图谱 </el-button>
            <el-button @click="exportGraphPNG"> 导出图谱 </el-button>
            <!-- <el-button @click="autoLayout"> 自动布局 </el-button> -->
          </div>
        </div>

        <div class="graph-container">
          <div ref="graphChartRef" class="echarts-graph"></div>
        </div>

        <!-- 节点提示框 -->
        <div
          v-if="showTooltip"
          class="node-tooltip"
          :style="{
            left: tooltipPosition.left + 'px',
            top: tooltipPosition.top + 'px',
          }"
        >
          <div class="tooltip-title">{{ tooltipData.title }}</div>
          <div class="tooltip-content">
            <p v-for="(value, key) in tooltipData.content" :key="key">
              <span class="tooltip-key">{{ key }}:</span> {{ value }}
            </p>
          </div>
        </div>
      </div>

      <!-- 右侧详情面板 -->
      <div v-if="detailVisible" class="detail-panel">
        <div class="detail-header">
          <h3>节点详情</h3>
          <el-button
            icon="Close"
            text
            @click="detailVisible = false"
            class="close-btn"
          />
        </div>

        <div class="detail-content">
          <!-- 加载状态 -->
          <el-skeleton v-if="loadingDetail" :rows="8" style="width: 100%" />

          <!-- 资产节点详情 -->
          <template v-else-if="nodeDetail.basic_info?.asset_ip">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="资产IP">
                {{ nodeDetail.basic_info.asset_ip }}
              </el-descriptions-item>
              <el-descriptions-item label="服务">
                {{ nodeDetail.basic_info.asset_service }}
              </el-descriptions-item>
              <el-descriptions-item label="部门">
                {{ nodeDetail.basic_info.department }}
              </el-descriptions-item>
              <el-descriptions-item label="责任人">
                {{ nodeDetail.basic_info.responsible_person }}
              </el-descriptions-item>
              <el-descriptions-item label="联系方式">
                {{ nodeDetail.basic_info.contact_info || "未知" }}
              </el-descriptions-item>
              <el-descriptions-item label="资产类型">
                {{ nodeDetail.basic_info.asset_type || "未知" }}
              </el-descriptions-item>
              <el-descriptions-item label="风险评分">
                <el-tag
                  :type="getRiskType(nodeDetail.risk_info?.risk_score || 0)"
                >
                  {{ nodeDetail.risk_info?.risk_score || 0 }}分 ({{
                    nodeDetail.risk_info?.risk_level_name || "未知"
                  }})
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div class="detail-section">
              <h4>风险信息</h4>
              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="漏洞总数">
                  {{ nodeDetail.risk_info?.total_vulnerabilities || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="严重漏洞">
                  {{ nodeDetail.risk_info?.critical_count || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="高危漏洞">
                  {{ nodeDetail.risk_info?.high_count || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="中危漏洞">
                  {{ nodeDetail.risk_info?.medium_count || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="低危漏洞">
                  {{ nodeDetail.risk_info?.low_count || 0 }}
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <div class="detail-section">
              <h4>关联漏洞 ({{ nodeDetail.vulnerabilities?.length || 0 }})</h4>
              <el-table
                :data="nodeDetail.vulnerabilities || []"
                size="small"
                border
              >
                <el-table-column label="CVE ID" prop="cve_id" />
                <el-table-column label="漏洞名称" prop="vul_name" />
                <el-table-column label="CVSS" prop="cvss_score" />
                <el-table-column label="严重程度" prop="severity_name" />
                <el-table-column label="匹配度" prop="match_score">
                  <template #default="{ row }">
                    {{ (row.match_score * 100).toFixed(0) }}%
                  </template>
                </el-table-column>
                <el-table-column label="状态" prop="status">
                  <template #default="{ row }">
                    <el-tag
                      :type="row.status === 'resolved' ? 'success' : 'warning'"
                      size="small"
                    >
                      {{ row.status === "resolved" ? "已修复" : "未修复" }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div
              v-if="nodeDetail.alerts && nodeDetail.alerts.length > 0"
              class="detail-section"
            >
              <h4>关联告警 ({{ nodeDetail.alerts.length }})</h4>
              <el-table :data="nodeDetail.alerts" size="small" border>
                <el-table-column label="告警ID" prop="alert_id" />
                <el-table-column label="CVE ID" prop="cve_id" />
                <el-table-column label="严重程度" prop="severity" />
                <el-table-column label="状态" prop="status">
                  <template #default="{ row }">
                    <el-tag
                      :type="row.status === 'resolved' ? 'success' : 'warning'"
                      size="small"
                    >
                      {{ row.status === "pending" ? "待处理" : "已处理" }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="created_at" />
              </el-table>
            </div>

            <div v-if="nodeDetail.remediation" class="detail-section">
              <h4>修复建议</h4>
              <el-tag type="danger" style="margin-bottom: 10px">
                优先级: {{ nodeDetail.remediation.priority }}
              </el-tag>
              <p style="margin-top: 10px">
                预计修复时间: {{ nodeDetail.remediation.estimated_fix_time }}
              </p>
              <ul style="margin-top: 10px; padding-left: 20px">
                <li
                  v-for="(action, index) in nodeDetail.remediation
                    .immediate_actions"
                  :key="index"
                >
                  {{ action }}
                </li>
              </ul>
            </div>
          </template>

          <!-- 漏洞节点详情 -->
          <template v-else-if="nodeDetail.cve_info?.cve_id">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="CVE ID">
                {{ nodeDetail.cve_info.cve_id }}
              </el-descriptions-item>
              <el-descriptions-item label="漏洞名称">
                {{ nodeDetail.cve_info.vul_name }}
              </el-descriptions-item>
              <el-descriptions-item label="CVSS评分">
                <el-tag :type="getSeverityType(nodeDetail.cve_info.cvss_score)">
                  {{ nodeDetail.cve_info.cvss_score }} ({{
                    nodeDetail.cve_info.severity_name
                  }})
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="来源">
                {{ nodeDetail.cve_info.source || "未知" }}
              </el-descriptions-item>
              <el-descriptions-item label="发布时间">
                {{ nodeDetail.cve_info.published_at || "未知" }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="detail-section">
              <h4>漏洞描述</h4>
              <p>{{ nodeDetail.cve_info.description || "暂无描述" }}</p>
            </div>

            <div class="detail-section">
              <h4>影响资产 ({{ nodeDetail.affected_assets?.length || 0 }})</h4>
              <el-table
                :data="nodeDetail.affected_assets || []"
                size="small"
                border
              >
                <el-table-column label="IP" prop="asset_ip" />
                <el-table-column label="服务" prop="asset_service" />
                <el-table-column label="部门" prop="department" />
                <el-table-column label="责任人" prop="responsible_person" />
                <el-table-column label="匹配度" prop="match_score">
                  <template #default="{ row }">
                    {{ (row.match_score * 100).toFixed(0) }}%
                  </template>
                </el-table-column>
                <el-table-column label="风险评分" prop="risk_score" />
              </el-table>
            </div>

            <div v-if="nodeDetail.remediation" class="detail-section">
              <h4>修复方案</h4>
              <p>
                <strong>解决方案:</strong> {{ nodeDetail.remediation.solution }}
              </p>
              <p v-if="nodeDetail.remediation.workaround">
                <strong>临时方案:</strong>
                {{ nodeDetail.remediation.workaround }}
              </p>
              <p v-if="nodeDetail.remediation.patch_available">
                <el-tag type="success">补丁可用</el-tag>
                <el-link
                  v-if="nodeDetail.remediation.patch_url"
                  :href="nodeDetail.remediation.patch_url"
                  target="_blank"
                  style="margin-left: 10px"
                >
                  下载补丁
                </el-link>
              </p>
            </div>

            <div
              v-if="nodeDetail.references && nodeDetail.references.length > 0"
              class="detail-section"
            >
              <h4>参考链接</h4>
              <ul style="padding-left: 20px">
                <li v-for="(ref, index) in nodeDetail.references" :key="index">
                  <el-link :href="ref" target="_blank">{{ ref }}</el-link>
                </li>
              </ul>
            </div>

            <div v-if="nodeDetail.statistics" class="detail-section">
              <h4>统计信息</h4>
              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="影响资产总数">
                  {{ nodeDetail.statistics.total_affected || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="高风险资产">
                  {{ nodeDetail.statistics.high_risk_assets || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="触发告警数">
                  {{ nodeDetail.statistics.alerts_triggered || 0 }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  onUnmounted,
  onBeforeUnmount,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useECharts } from "@pureadmin/utils";
import type { EChartsOption } from "echarts";
import type { Ref } from "vue";

// API调用
import {
  getAssetRiskGraphData,
  getAssetRiskFilterOptions,
  getAssetDetail,
  getVulnerabilityDetail,
  generateRiskReport,
  getAssetRiskStatistics,
} from "../../servers";

// 页面状态
const username = ref("张三");
const activeTab = ref("intelligence");
const loading = ref(false);
const loadingDetail = ref(false);
const detailVisible = ref(false);
const nodeDetail = ref<any>({});
const searchKeyword = ref("");
const currentLayout = ref("force");
const graphChartRef = ref<HTMLDivElement>();
let chartInstance: any = null;
const showTooltip = ref(false);
const tooltipData = ref({ title: "", content: {} });
const tooltipPosition = ref({ left: 0, top: 0 });

// 筛选条件
const filters = reactive({
  department: "",
  riskLevels: ["high", "medium"],
  assetTypes: [] as string[],
  severity: ["critical", "high"],
  limit: 30,
});

// 筛选选项
const filterOptions = reactive({
  departments: [] as any[],
  riskLevels: [
    { value: "high", label: "高风险", color: "#ff4d4f" },
    { value: "medium", label: "中风险", color: "#faad14" },
    { value: "low", label: "低风险", color: "#ffd666" },
    { value: "safe", label: "安全", color: "#52c41a" },
  ],
  assetTypes: [] as any[],
  severityLevels: [
    { value: "critical", label: "严重", color: "#ff4d4f" },
    { value: "high", label: "高危", color: "#faad14" },
    { value: "medium", label: "中危", color: "#ffd666" },
    { value: "low", label: "低危", color: "#52c41a" },
  ],
  limitOptions: [
    { value: 10, label: "10条" },
    { value: 30, label: "30条" },
    { value: 50, label: "50条" },
    { value: 100, label: "100条" },
  ],
});

// 统计数据
const statistics = reactive({
  departmentCount: 0,
  assetCount: 0,
  vulnerabilityCount: 0,
  alertCount: 0,
  // 新增字段
  totalAssets: 0,
  totalVulnerabilities: 0,
  avgVulnerabilitiesPerAsset: 0,
  riskDistribution: {
    high: 0,
    medium: 0,
    low: 0,
    safe: 0,
  },
  severityDistribution: {
    critical: 0,
    high: 0,
    medium: 0,
    low: 0,
  },
  topDepartments: [] as any[],
});

// ECharts 图表实例
const { setOptions, getInstance, resize } = useECharts(
  graphChartRef as Ref<HTMLDivElement>
);

// 获取节点样式
const getNodeStyle = (
  nodeType: string,
  severity?: string,
  cvssScore?: number,
  riskLevel?: string,
  riskScore?: number
) => {
  const styles: any = {
    department: {
      shape: "rect",
      size: [120, 80],
      color: "#1890ff",
      borderColor: "#fff",
      fontColor: "#fff",
      fontSize: 14,
    },
    asset: {
      shape: "rect",
      size: [120, 60],
      color: "#52c41a",
      borderColor: "#fff",
      fontColor: "#333",
      fontSize: 12,
    },
    vulnerability: {
      shape: "rect",
      size: cvssScore ? [100 + cvssScore * 5, 50] : [100, 50],
      color: "#faad14",
      borderColor: "#fff",
      fontColor: "#fff",
      fontSize: 12,
    },
    alert: {
      shape: "rect",
      size: [80, 45],
      color: "#ff4d4f",
      borderColor: "#fff",
      fontColor: "#fff",
      fontSize: 11,
    },
  };

  // 根据风险等级设置资产节点颜色
  if (nodeType === "asset" && riskLevel) {
    if (riskLevel === "high" || (riskScore && riskScore >= 80)) {
      styles.asset.color = "#ff4d4f";
      styles.asset.fontColor = "#fff";
    } else if (riskLevel === "medium" || (riskScore && riskScore >= 60)) {
      styles.asset.color = "#faad14";
      styles.asset.fontColor = "#fff";
    } else if (riskLevel === "low" || (riskScore && riskScore >= 40)) {
      styles.asset.color = "#ffd666";
      styles.asset.fontColor = "#333";
    } else {
      styles.asset.color = "#52c41a";
      styles.asset.fontColor = "#333";
    }
  }

  // 根据严重程度设置漏洞节点颜色
  if (nodeType === "vulnerability" && severity) {
    if (severity === "critical" || (cvssScore && cvssScore >= 9.0)) {
      styles.vulnerability.color = "#ff4d4f";
    } else if (severity === "high" || (cvssScore && cvssScore >= 7.0)) {
      styles.vulnerability.color = "#faad14";
    } else if (severity === "medium" || (cvssScore && cvssScore >= 4.0)) {
      styles.vulnerability.color = "#ffd666";
    } else {
      styles.vulnerability.color = "#52c41a";
    }
  }

  return styles[nodeType] || styles.asset;
};

// 获取边样式
const getEdgeStyle = (edgeType: string) => {
  const styles: any = {
    owns: {
      color: "#1890ff",
      width: 2,
      style: "solid",
    },
    affects: {
      color: "#ff4d4f",
      width: 4,
      style: "solid",
    },
    triggers: {
      color: "#faad14",
      width: 1,
      style: "dashed",
    },
  };

  return styles[edgeType] || styles.owns;
};

// 转换API数据为ECharts Graph格式
const transformGraphData = (apiData: any) => {
  if (!apiData) {
    return { nodes: [], links: [] };
  }

  const nodes = Array.isArray(apiData.nodes) ? apiData.nodes : [];
  const edges = Array.isArray(apiData.edges) ? apiData.edges : [];

  // 转换节点为ECharts格式
  const echartsNodes = nodes.map((node: any) => {
    const style = getNodeStyle(
      node.type,
      node.severity,
      node.cvss_score,
      node.risk_level,
      node.risk_score
    );
    const size = style.size instanceof Array ? style.size[0] : style.size;
    const height = style.size instanceof Array ? style.size[1] : size;

    return {
      id: node.id,
      name: node.label || node.id,
      symbolSize: [size, height], // 使用数组设置矩形大小 [宽度, 高度]
      symbol: "rect", // 使用矩形符号
      itemStyle: {
        color: style.color,
        borderColor: style.borderColor,
        borderWidth: 2,
      },
      label: {
        show: true,
        position: "inside",
        color: style.fontColor,
        fontSize: style.fontSize,
        formatter: (params: any) => {
          const name = params.name || "";
          // 如果名称太长，换行显示
          if (name.length > 15) {
            return name.substring(0, 15) + "\n" + name.substring(15);
          }
          return name;
        },
      },
      category: node.type,
      value: node.risk_score || node.cvss_score || 0,
      nodeType: node.type,
      metadata: node.metadata || {},
      severity: node.severity,
      cvssScore: node.cvss_score,
      riskLevel: node.risk_level,
      riskScore: node.risk_score,
      ip: node.ip,
      cveId: node.cve_id,
    };
  });

  // 转换边为ECharts格式
  const echartsLinks = edges.map((edge: any) => {
    const style = getEdgeStyle(edge.type);

    return {
      source: edge.source,
      target: edge.target,
      lineStyle: {
        color: style.color,
        width: style.width,
        type: style.style === "dashed" ? "dashed" : "solid",
      },
      edgeType: edge.type,
      matchScore: edge.match_score,
    };
  });

  return { nodes: echartsNodes, links: echartsLinks };
};

// 渲染ECharts图谱
const renderGraph = async (nodes: any[], links: any[]) => {
  const option: EChartsOption = {
    tooltip: {
      show: true,
      formatter: (params: any) => {
        if (params.dataType === "node") {
          const node = params.data;
          let content = `<div style="font-weight: bold; margin-bottom: 5px;">${node.name}</div>`;
          if (node.nodeType === "asset") {
            content += `<div>IP: ${
              node.ip || node.metadata?.ip || "未知"
            }</div>`;
            content += `<div>服务: ${node.metadata?.service || "未知"}</div>`;
            content += `<div>风险评分: ${node.riskScore || "未知"}</div>`;
            content += `<div>风险等级: ${node.riskLevel || "未知"}</div>`;
          } else if (node.nodeType === "vulnerability") {
            content += `<div>CVE ID: ${
              node.cveId || node.metadata?.cve_id || "未知"
            }</div>`;
            content += `<div>严重程度: ${node.severity || "未知"}</div>`;
            content += `<div>CVSS评分: ${node.cvssScore || "未知"}</div>`;
          } else if (node.nodeType === "department") {
            content += `<div>资产总数: ${
              node.metadata?.total_assets || 0
            }</div>`;
            content += `<div>高风险资产: ${
              node.metadata?.high_risk_count || 0
            }</div>`;
          } else if (node.nodeType === "alert") {
            content += `<div>告警ID: ${
              node.metadata?.alert_id || "未知"
            }</div>`;
            content += `<div>状态: ${node.metadata?.status || "未知"}</div>`;
          }
          return content;
        }
        return params.data.label?.formatter || "";
      },
    },
    series: [
      {
        type: "graph",
        layout: currentLayout.value === "force" ? "force" : "circular",
        data: nodes,
        links: links,
        categories: [
          { name: "department", itemStyle: { color: "#1890ff" } },
          { name: "asset", itemStyle: { color: "#52c41a" } },
          { name: "vulnerability", itemStyle: { color: "#faad14" } },
          { name: "alert", itemStyle: { color: "#ff4d4f" } },
        ],
        roam: true,
        label: {
          show: true,
          position: "inside",
          formatter: "{b}",
          fontSize: 12,
        },
        labelLayout: {
          hideOverlap: false,
        },
        emphasis: {
          focus: "adjacency",
          lineStyle: {
            width: 4,
          },
        },
        lineStyle: {
          curveness: 0.3,
        },
        force: {
          repulsion: 2000,
          gravity: 0.1,
          edgeLength: 150,
          layoutAnimation: true,
        },
        circular: {
          rotateLabel: true,
        },
      },
    ],
  };

  setOptions(option);
  chartInstance = getInstance();
  setupChartEvents(); // 设置事件监听

  // 确保图表正确填充容器
  await nextTick();
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 加载图谱数据
const loadGraphData = async () => {
  try {
    loading.value = true;

    // 构建请求参数
    const params = {
      department: filters.department || undefined,
      risk_levels:
        filters.riskLevels.length > 0 ? filters.riskLevels : undefined,
      asset_types:
        filters.assetTypes.length > 0 ? filters.assetTypes : undefined,
      severity_filter:
        filters.severity.length > 0 ? filters.severity : undefined,
      limit: filters.limit,
    };

    const res = await getAssetRiskGraphData(params);

    const { nodes, links } = transformGraphData(res.data);

    // 更新统计数据
    if (res.data.statistics) {
      statistics.departmentCount = res.data.statistics.department_count || 0;
      statistics.assetCount = res.data.statistics.asset_count || 0;
      statistics.vulnerabilityCount =
        res.data.statistics.vulnerability_count || 0;
      statistics.alertCount = res.data.statistics.alert_count || 0;
    }

    // 渲染图谱
    await nextTick();
    if (nodes.length > 0) {
      await renderGraph(nodes, links);
      // 再次确保图表正确填充容器
      await nextTick();
      if (chartInstance) {
        chartInstance.resize();
      }
    } else {
      ElMessage.warning("暂无数据");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取图谱数据失败");
  } finally {
    loading.value = false;
  }
};

// 获取筛选选项
const loadFilterOptions = async () => {
  try {
    const res = await getAssetRiskFilterOptions();

    // 更新部门选项
    if (res.data.departments) {
      filterOptions.departments = res.data.departments.map((item: any) => ({
        value: item,
        label: item,
      }));
    }

    // 更新风险等级选项
    if (res.data.risk_levels) {
      filterOptions.riskLevels = res.data.risk_levels.map((item: any) => ({
        value: item.value,
        label: item.label,
        color: item.color,
      }));
    }

    // 更新资产类型选项
    if (res.data.asset_types) {
      filterOptions.assetTypes = res.data.asset_types.map((item: any) => ({
        value: item.value,
        label: item.label,
        count: item.count,
      }));
    }

    // 更新漏洞严重程度选项
    if (res.data.severity_levels) {
      filterOptions.severityLevels = res.data.severity_levels.map(
        (item: any) => ({
          value: item.value,
          label: item.label,
          color: item.color,
        })
      );
    }
  } catch (error: any) {
    console.error("获取筛选选项失败:", error);
  }
};

// 获取统计数据
const loadStatistics = async () => {
  try {
    const res = await getAssetRiskStatistics({
      department: filters.department || undefined,
    });
    if (res.code === 200 || res.code === 2000) {
      const data = res.data;
      // 更新基础统计
      statistics.totalAssets = data.total_assets || 0;
      statistics.totalVulnerabilities = data.total_vulnerabilities || 0;
      statistics.avgVulnerabilitiesPerAsset =
        data.avg_vulnerabilities_per_asset || 0;

      // 更新风险分布
      if (data.risk_distribution) {
        statistics.riskDistribution.high = data.risk_distribution.high || 0;
        statistics.riskDistribution.medium = data.risk_distribution.medium || 0;
        statistics.riskDistribution.low = data.risk_distribution.low || 0;
        statistics.riskDistribution.safe = data.risk_distribution.safe || 0;
      }

      // 更新严重程度分布
      if (data.severity_distribution) {
        statistics.severityDistribution.critical =
          data.severity_distribution.critical || 0;
        statistics.severityDistribution.high =
          data.severity_distribution.high || 0;
        statistics.severityDistribution.medium =
          data.severity_distribution.medium || 0;
        statistics.severityDistribution.low =
          data.severity_distribution.low || 0;
      }

      // 更新顶级部门
      if (data.top_departments && Array.isArray(data.top_departments)) {
        statistics.topDepartments = data.top_departments;
      }

      // 更新部门数量（基于top_departments长度或单独字段）
      statistics.departmentCount = statistics.topDepartments.length;

      // 更新资产和漏洞数量（如果API返回了这些数据）
      statistics.assetCount = statistics.totalAssets;
      statistics.vulnerabilityCount = statistics.totalVulnerabilities;
    }
  } catch (error: any) {
    console.error("获取统计数据失败:", error);
  }
};

// 节点点击事件（通过ECharts事件绑定）
const setupChartEvents = () => {
  if (!chartInstance) return;

  chartInstance.off("click");
  chartInstance.on("click", async (params: any) => {
    if (params.dataType === "node") {
      const node = params.data;
      try {
        loadingDetail.value = true;
        let res;

        // 根据节点类型调用不同的接口
        if (node.nodeType === "asset") {
          // 资产节点使用 asset_ip 获取详情
          const assetIp =
            node.ip || node.metadata?.ip || node.id.replace("asset_", "");
          res = await getAssetDetail({
            asset_ip: assetIp,
          });
        } else if (node.nodeType === "vulnerability") {
          // 漏洞节点使用 cve_id 获取详情
          const cveId =
            node.cveId || node.metadata?.cve_id || node.id.replace("vuln_", "");
          res = await getVulnerabilityDetail({
            cve_id: cveId,
          });
        } else {
          // 其他节点类型（部门、告警）暂不显示详情
          ElMessage.info("该节点类型暂不支持查看详情");
          return;
        }

        if (res.code === 2000) {
          nodeDetail.value = res.data;
          detailVisible.value = true;
        }
      } catch (error: any) {
        ElMessage.error(error?.message || "获取节点详情失败");
      } finally {
        loadingDetail.value = false;
      }
    } else if (params.dataType === "edge") {
      const link = params.data;
      ElMessage.info(`关系: ${link.label?.formatter || link.edgeType}`);
    }
  });
};

// 搜索节点（本地搜索）
const searchNodes = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  if (!chartInstance) {
    return;
  }

  try {
    const option = chartInstance.getOption();
    const nodes = option.series[0].data || [];
    const keyword = searchKeyword.value.toLowerCase();

    // 在现有节点中搜索
    const matchedNodes = nodes.filter((node: any) => {
      const name = (node.name || "").toLowerCase();
      const ip = (node.ip || "").toLowerCase();
      const cveId = (node.cveId || "").toLowerCase();
      return (
        name.includes(keyword) ||
        ip.includes(keyword) ||
        cveId.includes(keyword)
      );
    });

    if (matchedNodes.length > 0) {
      // 高亮第一个匹配的节点
      const firstNodeIndex = nodes.findIndex(
        (n: any) => n.id === matchedNodes[0].id
      );
      if (firstNodeIndex >= 0) {
        chartInstance.dispatchAction({
          type: "highlight",
          dataIndex: firstNodeIndex,
        });

        // 3秒后取消高亮
        setTimeout(() => {
          if (chartInstance) {
            chartInstance.dispatchAction({
              type: "downplay",
              dataIndex: firstNodeIndex,
            });
          }
        }, 3000);
      }
      ElMessage.success(`找到 ${matchedNodes.length} 个匹配节点`);
    } else {
      ElMessage.info("未找到匹配的节点");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "搜索节点失败");
  }
};

// 刷新图谱
const refreshGraph = () => {
  loadGraphData();
};

// 切换布局
const changeLayout = (layoutName: string) => {
  currentLayout.value = layoutName;
  loadGraphData(); // 重新加载数据以应用新布局
};

// 自动布局
const autoLayout = () => {
  if (chartInstance) {
    // ECharts会自动重新布局
    chartInstance.resize();
  }
};

// 导出图谱PNG
const exportGraphPNG = () => {
  if (chartInstance) {
    const url = chartInstance.getDataURL({
      type: "png",
      pixelRatio: 2,
      backgroundColor: "#fff",
    });
    const link = document.createElement("a");
    link.href = url;
    link.download = `asset_risk_graph_${new Date().getTime()}.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success("图谱导出成功");
  }
};

// 导出JSON数据（导出当前图谱数据）
const exportGraphJSON = async () => {
  try {
    if (!chartInstance) {
      ElMessage.warning("暂无图谱数据");
      return;
    }

    const option = chartInstance.getOption();
    const nodes = option.series[0].data || [];
    const links = option.series[0].links || [];

    const graphData = {
      nodes,
      links,
      exportTime: new Date().toISOString(),
      filters: {
        department: filters.department,
        riskLevels: filters.riskLevels,
        assetTypes: filters.assetTypes,
        severity: filters.severity,
        limit: filters.limit,
      },
    };

    // 创建下载链接
    const blob = new Blob([JSON.stringify(graphData, null, 2)], {
      type: "application/json",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `asset_risk_graph_${new Date().getTime()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    ElMessage.success("JSON数据导出成功");
  } catch (error: any) {
    ElMessage.error(error?.message || "导出JSON数据失败");
  }
};

// 筛选相关方法
const handleFilterChange = () => {
  // 可以在这里添加防抖处理
};

const applyFilters = () => {
  loadGraphData();
  loadStatistics(); // 重新加载统计数据
};

const resetFilters = () => {
  filters.department = "";
  filters.riskLevels = ["high", "medium"];
  filters.assetTypes = [];
  filters.severity = ["critical", "high"];
  filters.limit = 30;

  // 重新加载数据
  loadGraphData();
  loadStatistics(); // 重新加载统计数据
};

// 节点详情页操作
const viewFullDetail = () => {
  // 查看完整详情逻辑
  ElMessage.info("跳转到完整详情页面");
};

const jumpToIntelligence = () => {
  // 跳转到情报库逻辑
  ElMessage.info("跳转到情报库");
};

// 辅助方法：根据评分获取严重程度标签类型
const getSeverityType = (score: number) => {
  if (score >= 9.0) return "danger";
  if (score >= 7.0) return "warning";
  if (score >= 4.0) return "info";
  return "success";
};

// 辅助方法：根据风险评分获取标签类型
const getRiskType = (score: number) => {
  if (score >= 80) return "danger";
  if (score >= 60) return "warning";
  if (score >= 40) return "info";
  return "success";
};

// 窗口大小变化监听
let resizeTimer: any = null;
const handleResize = () => {
  if (resizeTimer) {
    clearTimeout(resizeTimer);
  }
  resizeTimer = setTimeout(() => {
    if (chartInstance) {
      chartInstance.resize();
    }
  }, 100);
};

// 初始化
onMounted(async () => {
  loadFilterOptions();
  loadStatistics();
  // 等待组件初始化完成，确保容器尺寸已确定
  nextTick();
  // 添加窗口大小变化监听
  window.addEventListener("resize", handleResize);
  loadGraphData();
});

// 组件卸载时清理
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  if (resizeTimer) {
    clearTimeout(resizeTimer);
  }
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});

// 暴露 resizeChart 方法供父组件调用
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

defineExpose({
  resizeChart,
});
</script>

<style scoped lang="scss">
.intelligence-graph-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.navbar-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .navbar-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: #333;
    }

    .user-info {
      color: #666;
      font-size: 14px;
    }
  }
}

.tabs-container {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 10px 20px 0;
}

.graph-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 150px);
}

.filter-panel {
  width: 280px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;

  label {
    font-size: 14px;
    color: #666;
    font-weight: 500;
  }

  .el-select,
  .el-input {
    width: 100%;
  }
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.statistics-section,
.legend-section {
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 12px;

  h3 {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 500;
  }

  h4 {
    font-size: 13px;
    color: #555;
    margin: 12px 0 8px 0;
    font-weight: 500;
  }

  .statistics-list {
    padding: 0;
    margin: 0;

    .statistics-item {
      font-size: 13px;
      color: #666;
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 0;
      line-height: 1.5;
    }
  }
}

.statistics-subsection {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e8e8e8;

  &:first-of-type {
    margin-top: 0;
    padding-top: 0;
    border-top: none;
  }

  .statistics-list {
    padding: 0;
    margin: 0;

    .statistics-item {
      font-size: 13px;
      color: #666;
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 0;
      line-height: 1.5;
    }
  }
}

.risk-badge,
.severity-badge {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;

  &.high {
    background-color: #ff4d4f;
  }

  &.medium {
    background-color: #faad14;
  }

  &.low {
    background-color: #ffd666;
  }

  &.safe {
    background-color: #52c41a;
  }

  &.critical {
    background-color: #ff4d4f;
  }
}

.legend-icon {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;

  &.department {
    background-color: #1890ff;
    border-radius: 2px;
  }

  &.asset {
    background-color: #52c41a;
    border-radius: 2px;
  }

  &.vulnerability {
    background-color: #faad14;
    border-radius: 2px;
  }

  &.alert {
    background-color: #ff4d4f;
    border-radius: 2px;
  }
}

.graph-area {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.graph-toolbar {
  padding: 10px 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.graph-actions {
  display: flex;
  align-items: center;
  gap: 5px;
}

.graph-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.echarts-graph {
  width: 100%;
  height: 100%;
  min-height: 600px;
}

.node-tooltip {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 1000;
  pointer-events: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  max-width: 250px;

  .tooltip-title {
    font-weight: bold;
    margin-bottom: 5px;
    padding-bottom: 5px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  }

  .tooltip-content {
    p {
      margin: 3px 0;
      line-height: 1.4;

      .tooltip-key {
        color: #ccc;
        display: inline-block;
        width: 60px;
      }
    }
  }
}

.detail-panel {
  width: 400px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.detail-header {
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
  }

  .close-btn {
    color: #999;
  }
}

.detail-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;

  .detail-section {
    margin-top: 16px;

    h4 {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;
    }
  }

  .detail-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
  }
}

.el-table {
  font-size: 12px;

  .el-table__cell {
    padding: 6px 0;
  }
}

.el-descriptions {
  margin-bottom: 16px;

  .el-descriptions__label {
    font-weight: 500;
  }
}

@media (max-width: 1600px) {
  .filter-panel {
    width: 240px;
  }

  .detail-panel {
    width: 350px;
  }

  .search-input {
    width: 220px;
  }
}
</style>
